package com.yzk.train.business.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.yzk.train.business.utils.MathGenerator;
import com.yzk.train.common.response.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Resource
    public StringRedisTemplate stringRedisTemplate;

    @GetMapping("/get/{codeToken}")
    public void getCaptcha(@PathVariable String codeToken, HttpServletResponse response) throws IOException {
        // 生成验证码
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(120, 33, 4, 3);
        MathGenerator mathGenerator = new MathGenerator();
        captcha.setGenerator(mathGenerator);
        // 保存验证码到Redis中，并设置过期时间
        stringRedisTemplate.opsForValue().set(codeToken, captcha.getCode(), 30, TimeUnit.SECONDS);
        // 设置响应头，返回验证码图片给前端
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(captcha.getImageBytes());
        outputStream.flush();
        outputStream.close();
    }

    @GetMapping("/verify/{codeToken}/{input}")
    public Result<String> verify(@PathVariable String codeToken, @PathVariable String input) {
        MathGenerator mathGenerator = new MathGenerator();
        String code = stringRedisTemplate.opsForValue().get(codeToken);
        if (code == null) return Result.fail("验证码不合法");
        // 解析验证码
        boolean verify = mathGenerator.verify(code, input);
        if (verify) {
            stringRedisTemplate.delete(codeToken);
            return Result.ok(null);
        } else {
            return Result.fail("验证码错误");
        }
    }
}
